package com.iretailer.report.quartz.horizon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iretailer.report.quartz.horizon.common.ClientHttpMethod;
import com.iretailer.report.quartz.horizon.common.Signer;
import com.iretailer.report.quartz.horizon.model.VistorsModel;
import com.iretailer.report.util.TimeUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.SortedMap;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Auther: xjw
 * @Date: 2019/9/27 0027 14:24
 * @Description:
 */
public class SampleCode {
    private final static Logger log = LoggerFactory.getLogger(SampleCode.class);

    public static void main(String[] args) throws Exception {
        Signer signer = new Signer(Settings.AK, Settings.SK);


        // 创建人脸库
//        creatFaceSet(signer);
//        查询人脸库列表
//        facesets(signer);
//        查询某个人脸库的信息
//        faceset_id(signer);
        // 关联人脸库到设备空间
//        attach_space(signer);
        // 获取人脸库中人员列表
//        facesetFaces(signer);


        // 启用客流统计分析
//        flow_enable(signer);
        // 总客流查询
//        count(signer);
        // 去重客流查询
//        getPersonCount(signer);
//        person_count(signer);
        // 查询到店记录
        deviceVisitors(signer);


//        String clientId = TimeUtil.localDateTime_format(LocalDateTime.now(), "yyyyMMddHHmmss");
//        subVisitorsSample02(signer, clientId);
//        System.out.println(clientId);
//        String result = subVisitorsSample(signer, clientId);
//        System.out.println(result);
//        wsVistorsSample(signer, clientId);
    }


    /**
     * 创建人脸库
     */
    public static void creatFaceSet(Signer signer) {
        String APIURL = "/openapi/v1/facesets";
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        JSONObject body = new JSONObject();
        body.put("name", "testname");
        body.put("extra", "extra");
        body.put("description", "description");
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpPOST(String.class, APIURL, headers, params, JSON.toJSONString(body));
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询单个人脸库的信息
     *
     * @param signer
     */
    public static void faceset_id(Signer signer) {
        String APIURL = String.format("/openapi/v1/facesets/%s", "5da40d49e7738a00099a0ddd");
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
//        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, APIURL, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询人脸库列表
     *
     * @param signer
     */
    public static void facesets(Signer signer) {
        String facesets = "/openapi/v1/facesets";
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        params.put("current", "1");
        params.put("per_page", "20");
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, facesets, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关联人脸库到设备空间
     *
     * @param signer
     */
    public static void attach_space(Signer signer) {
        String APIURL = "/openapi/v1/analysis_tools/attach_space";
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        try {
            JSONObject body = new JSONObject();
            body.put("space_ids", Arrays.asList("d104e5125d789e5c5a579004_YiRGEJCF"));
            body.put("faceset_ids", Arrays.asList("5da40d49e7738a00099a0ddd"));
            result = ClientHttpMethod.getHttpMethod(signer).httpPOST(String.class, APIURL, headers, params, JSON.toJSONString(body));
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户列表
     *
     * @param signer
     */
    public static void facesetFaces(Signer signer) {
        String facesets = String.format("/openapi/v1/facesets/%s/faces", "5d8da85621a6fc000919e963");
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        params.put("current", "1");
        params.put("per_page", "100");
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, facesets, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启用客流统计分析
     *
     * @param signer
     */
    public static void flow_enable(Signer signer) {
        String APIURL = "/openapi/v1/analysis_tools/enable";
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        try {
            JSONObject body = new JSONObject();
            body.put("space_id", "d104e5125d789e5c5a579004_YiRGEJCF");
            result = ClientHttpMethod.getHttpMethod(signer).httpPOST(String.class, APIURL, headers, params, JSON.toJSONString(body));
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 总客流查询
     *
     * @param signer
     */
    public static void count(Signer signer) {
        String APIURL = String.format("/openapi/v1/analysis_tools/%s/count", "0694E001020110625L");
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);

        params.put("cycle", "hour");
        params.put("end_time", "2019-09-29T17:00:00+08:00");
        params.put("start_time", "2019-09-29T10:00:00+08:00");
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, APIURL, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getPersonCount(Signer signer) {
        String API_DEVICE_SPACES_LIST = String.format("/openapi/v1/analysis_tools/%s/person_count", "d104e5125d789e5c5a579004_YiRGEJCF");
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);

        params.put("cycle", "hour");
//        params.put("device_sns", "d104e5125d789e5c5a579004_YiRGEJCF");
        params.put("end_time", "2019-09-29T17:00:00+08:00");
        params.put("filter_whitelist", "false");
        params.put("only_capture", "true");
        params.put("start_time", "2019-09-29T10:00:00+08:00");

        try {
            String authorization = signer.Sign(HttpMethod.GET, API_DEVICE_SPACES_LIST, params, headers);
//            System.out.println(authorization);
//            String path = "http://" + headers.get(Settings.HOST) + API_DEVICE_SPACES_LIST +
//                    "?" + Signer.getCanonicalQueryString(params, "UTF-8") + "&authorization=" + authorization;
            String p = Signer.getCanonicalQueryString(params, "UTF-8");
            String path = String.format("http://%s%s?%s&authorization=%s", headers.get(Settings.HOST), API_DEVICE_SPACES_LIST, p, authorization);
            log.error(path);
            URL url = new URL(path); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            // connection.setRequestProperty("设置请求头key", "请求头value");
//            connection.setRequestProperty("authorization", authorization);
            connection.connect();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            log.error(sb.toString());
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败!");
            return "error";
        }
    }

    /**
     * 去重客流查询
     *
     * @param signer
     */
    public static void person_count(Signer signer) throws Exception {
        String API_COUNT = String.format("/openapi/v1/analysis_tools/%s/person_count", "d104e5125d789e5c5a579004_YiRGEJCF");
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);

        params.put("cycle", "hour");
//        params.put("device_sns", "d104e5125d789e5c5a579004_YiRGEJCF");
        params.put("end_time", "2019-09-29T17:00:00+08:00");
        params.put("filter_whitelist", "false");
        params.put("only_capture", "true");
        params.put("start_time", "2019-09-29T10:00:00+08:00");

        ResponseEntity<String> result = null;

        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, API_COUNT, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 到店记录查询
     * // 设备号查询
     *
     * @return
     */
    public static void deviceVisitors(Signer signer) {
        String APIURL = String.format("/openapi/v1/analysis_tools/%s/visitors", "0694E001020110625L");
        SortedMap<String, String> params = new TreeMap<>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        params.put("current", "1");
        params.put("per_page", "20");
        params.put("end_time", TimeUtil.getISODateTime(TimeUtil.parse_LocalDateTime("2019-10-14 11:00:00"),OffsetDateTime.now().getOffset()));
        params.put("start_time", TimeUtil.getISODateTime(TimeUtil.parse_LocalDateTime("2019-10-14 10:00:00"),OffsetDateTime.now().getOffset()));
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, APIURL, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发起到店记录订阅
     */
    public static String subVisitorsSample(Signer signer, String clientId) {
        String API_VISITORS_SUB = "/openapi/v1/analysis_tools/visitors/sub";
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(URLEncoder.encode("content-type"), URLEncoder.encode("application/json"));
        headers.put(Settings.HOST, Settings.PAAS_HOST);

        try {
            String authorization = signer.Sign(HttpMethod.PUT, API_VISITORS_SUB, params, headers);
            String path = "http://" + headers.get(Settings.HOST) + API_VISITORS_SUB;
            URL url = new URL(path); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // connection.setRequestProperty("设置请求头key", "请求头value");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(RequestParam.HTTP_METHOD_PUT);
            connection.setRequestProperty("authorization", authorization);
            connection.setRequestProperty(URLEncoder.encode("content-type"), URLEncoder.encode("application/json"));
            connection.setRequestProperty(Settings.HOST, Settings.PAAS_HOST);
            connection.connect();
            // 修改为自己要订阅的topic的json 报文
            String body = "{\"topic_name\":\"device\",\"topic_id\":\"0694E001020110625L\",\"client_id\":\"" + clientId + "\"}";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败!");
            return "error";
        }
    }

    public static void subVisitorsSample02(Signer signer, String clientId) {
        String API_VISITORS_SUB = "/openapi/v1/analysis_tools/visitors/sub";
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        String body = "{\"topic_name\":\"device\",\"topic_id\":\"0694E001020110625L\",\"client_id\":\"" + clientId + "\"}";
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpPUT(String.class, API_VISITORS_SUB, headers, params, body);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 订阅到店记录推送
     *
     * @param clientId
     */
    public static void wsVistorsSample(Signer signer, String clientId) {
        String url = Settings.WEBSOCKET_PATH;
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.WEBSOCKET_HOST);
        WebSocketClient client = null;
        try {
            // Get the authentication string
            String authorization = signer.Sign(HttpMethod.GET, "/ws", params, headers);
            url += "?authorization=" + authorization;
            headers.put("hobot_xpush_client_id", clientId);

            client = new WebSocketClient(new URI(url), new Draft_6455(), headers) {

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("Handshake success");
                }

                @Override
                public void onMessage(String msg) {
                    log.error(msg);
                    VistorsModel vistorsModel = JSON.parseObject(msg, VistorsModel.class);
                    log.error("Received message: {}", JSON.toJSONString(vistorsModel));
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("Websocket connection has been closed");
                }

                @Override
                public void onError(Exception e) {
                    System.err.println("Websocket error:" + e);
                    System.out.println("An error occurred, websocket connection has been closed");
                }
            };
        } catch (URISyntaxException e) {
            System.err.println("Websocket error:" + e);
        } catch (Exception e) {
            e.printStackTrace();
        }

        client.connect();
        while (!client.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("connecting...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
    }


}
